<?php

namespace Wintel\RestBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * ClassIvrController
 * @package Wintel\RestBundle\Controller
 */
class IvrController extends Controller
{

    /**
     * 添加IVR流程
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function addAction(request $request)
    {
        $conn = $this->get("doctrine.dbal.default_connection");

        $vcc_code = $request->get("vcc_code", 0);
        $ivr_name = $request->get('ivr_name', '');
        $ivr_code = $request->get('ivr_code', '');
        $remark   = $request->get('remark', '');
        $if_work   = $request->get('if_work', 0);

        /* 验证企业是否存在 */
        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        /* 验证IVR流程名称 */
        if (empty($ivr_name)) {
            $ret = array(
                'code' => 403,
                'message' => 'IVR流程名称为空',
            );
            return new JsonResponse($ret);
        }

        /* 验证IVR流程名称是否重复 */
        $where = " vcc_id = :vcc_id AND ivr_name = :ivr_name AND ivr_id <> :ivr_id";
        $par_arr = array('vcc_id'=>$vid, 'ivr_name'=>$ivr_name,'ivr_id'=>$vid);
        $msg = $this->get('validator.custom')->existIvr($where, $par_arr, 404);
        if (!empty($msg)) {
            return new JsonResponse($msg);
        }

        try {
            $add_time = time();
            $data = array(
                'vcc_id' => $vid,
                'vcc_code' => $vcc_code,
                'ivr_name' => $ivr_name,
                'ivr_code' => $ivr_code,
                'remark' => $remark,
                'add_time' => $add_time,
                'if_work' => (int)$if_work,
            );

            $conn->insert('win_ivr', $data);
            $ivr_id = $conn->lastInsertId();

            $ret = array(
                'code' => 200,
                'message' => 'ok',
                'data'=>$ivr_id,
            );
            return new JsonResponse($ret);
        } catch (Exception $e) {
            $conn->rollback();
            $ret = array(
                'code' => 405,
                'message' => '添加ivr流程失败['.$e->getMessage().']'
            );
            return new JsonResponse($ret);
        }
    }

    /**
     * 编辑IVR流程
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function editAction(request $request)
    {
        $conn = $this->get("doctrine.dbal.default_connection");

        $vcc_code = $request->get("vcc_code", 0);
        $ivr_id   = $request->get('ivr_id', '');
        $ivr_name = $request->get('ivr_name', '');
        $ivr_code = $request->get('ivr_code', '');
        $remark   = $request->get('remark', '');
        $if_work   = $request->get('if_work', 0);

        /* 验证企业是否存在 */
        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        /* 验证企业是否存在该IVR流程 */
        $count = $conn->fetchColumn(
            'SELECT count(*) '.
            'FROM win_ivr '.
            'WHERE vcc_id = :vcc_id AND ivr_id = :ivr_id ',
            array('vcc_id'=>$vid,'ivr_id'=>$ivr_id)
        );

        if (empty($count)) {
            $ret = array(
                'code' => 403,
                'message' => 'IVR流程不存在',
            );
            return new JsonResponse($ret);
        }

        /* 验证IVR流程名称 */
        if (empty($ivr_name)) {
            $ret = array(
                'code' => 404,
                'message' => 'IVR流程名称为空',
            );
            return new JsonResponse($ret);
        }

        /* 验证IVR流程名称是否重复 */
        $where = " vcc_id = :vcc_id AND ivr_name = :ivr_name AND ivr_id <> :ivr_id";
        $par_arr = array('vcc_id'=>$vid, 'ivr_name'=>$ivr_name,'ivr_id'=>$ivr_id);
        $msg = $this->get('validator.custom')->existIvr($where, $par_arr, 405);
        if (!empty($msg)) {
            return new JsonResponse($msg);
        }

        $data = array(
            'ivr_name' => $ivr_name,
            'ivr_code' => $ivr_code,
            'remark' => $remark,
            'if_work' => (int)$if_work,
        );

        $num = $conn->update('win_ivr', $data, array('vcc_id'=>$vid,'ivr_id'=>$ivr_id));

        if ($num > 0) {
            $ret = array(
                'code' => 200,
                'message' => 'ok',
                'data'=>$ivr_id,
            );
            return new JsonResponse($ret);
        } else {
            $ret = array(
                'code' => 406,
                'message' => '编辑IVR流程失败',
            );
            return new JsonResponse($ret);
        }
    }

    /**
     * 删除IVR流程
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function deleteAction(request $request)
    {
        $conn = $this->get("doctrine.dbal.default_connection");

        $vcc_code = $request->get("vcc_code", 0);
        $ivr_id   = $request->get('ivr_id', 0);


        /* 验证企业是否存在 */
        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        /* 有批量删除的情况 */
        $ivr_arr = json_decode($ivr_id);
        $ivr_arr = json_last_error() || !is_array($ivr_arr) ? array((int)$ivr_id) : $ivr_arr;
        if (empty($ivr_arr)) {
            return new JsonResponse(array('code'=>403, 'message'=>'流程id为空'));
        }

        $errorMsg = array();

        foreach ($ivr_arr as $v) {
            //验证技能组id 是否属于该企业；
            $vcc_id = $conn->fetchColumn(
                'SELECT vcc_id '.
                'FROM win_ivr '.
                'WHERE ivr_id = :ivr_id',
                array('ivr_id'=>$v)
            );

            if ($vcc_id != $vid) {
                $ret = array(
                    'code' => 404,
                    'message' => '流程不属于该企业',
                );
                $errorMsg[] = array_merge($ret, array('ivr_id'=>$v));
                continue;
            }

            $conn->delete('win_ivr', array('ivr_id'=>$v));
        }

        return new JsonResponse(array('code'=>500,'message'=>'总结果','data'=>$errorMsg));
    }

    /**
     * 获取IVR流程数据
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function listAction(request $request)
    {
        $conn = $this->get("doctrine.dbal.default_connection");

        $vcc_code = $request->get("vcc_code", '');
        $ivr_id   = $request->get("ivr_id", 0);
        $info     = $request->get('info', '');

        /* 验证企业是否存在 */
        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        //分页搜索相关信息；
        $addInfo = array();
        if (!empty($info)) {
            $addInfo = json_decode($info, true);
            if (json_last_error()) {
                return new JsonResponse(array('code' => 404, 'message'=>'info格式非json'));
            }
        }
        $where  = '';
        $where .= !empty($ivr_id) ? " AND ivr_id = :ivr_id " : '';
        $params = !empty($ivr_id) ? array('vcc_id'=>$vid, 'ivr_id'=>$ivr_id) : array('vcc_id'=>$vid);

        if (isset($addInfo['filter'])) {
            $where.= isset($addInfo['filter']['ivr_name']) && !empty($addInfo['filter']['ivr_name']) ? " AND ivr_name like '%".$addInfo['filter']['ivr_name']."%'" : '';
        }

        $count = $conn->fetchColumn(
            'SELECT count(*) '.
            'FROM win_ivr '.
            'WHERE vcc_id = :vcc_id '.$where,
            $params
        );

        $page = $this->get("validator.extend.custom")->getPageInfo($count, 'win_ivr', $addInfo);
        $page['sort'] = $page['sort'] !=1 ? $page['sort'] : $page['sort'];
        $list = $conn->fetchAll(
            'SELECT ivr_id,ivr_name,ivr_code,remark,update_time,if_refresh,if_work FROM win_ivr '.
            'WHERE vcc_id = :vcc_id '.$where.
            ' ORDER BY '.$page['sort'].' '.$page['order'].' LIMIT '.$page['start'].','.$page['limit'],
            $params
        );

        $ret = array(
            'code' => 200,
            'message' =>'ok',
            'total' => $count,
            'data' => $list,
        );
        return new JsonResponse($ret);
    }

    /**
     * 获取IVR流程配置信息
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function infoAction(request $request)
    {
        $conn = $this->get("doctrine.dbal.default_connection");

        $vcc_code = $request->get("vcc_code", 0);
        $ivr_id   = $request->get('ivr_id', 0);

        /* 验证企业是否存在 */
        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        /* 验证企业是否存在该IVR流程 */
        $count = $conn->fetchColumn(
            'SELECT count(*) '.
            'FROM win_ivr '.
            'WHERE vcc_id = :vcc_id AND ivr_id = :ivr_id ',
            array('vcc_id'=>$vid,'ivr_id'=>$ivr_id)
        );

        if (empty($count)) {
            $ret = array(
                'code' => 403,
                'message' => 'IVR流程不存在',
            );
            return new JsonResponse($ret);
        }

        $ivr_info = $conn->fetchAssoc(
            'SELECT * FROM win_ivr WHERE ivr_id = :ivr_id AND vcc_id = :vcc_id',
            array('ivr_id'=>$ivr_id,'vcc_id'=>$vid)
        );

        if (empty($ivr_info)) {
            $ret = array(
                'code' => 404,
                'message' => 'IVR流程不存在',
            );
        } else {
            $ret = array(
                'code' => 200,
                'message' => 'ok',
                'data'=>$ivr_info
            );
        }

        return new JsonResponse($ret);
    }

    /**
     * 保存流程配置
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function saveAction(request $request)
    {
        $conn = $this->get("doctrine.dbal.default_connection");

        $vcc_code    = $request->get("vcc_code", 0);
        $ivr_id      = $request->get('ivr_id', 0);
        $ivr_info    = $request->get('ivr_info', 0);
        $ivr_content = $request->get('ivr_content', 0);

        /* 验证企业是否存在 */
        $msg = $vid = $this->get('validator.custom')->checkVccCode($vcc_code);
        if (!empty($msg) && is_array($msg)) {
            return new JsonResponse($msg);
        }

        /* 验证企业是否存在该IVR流程 */
        $count = $conn->fetchColumn(
            'SELECT count(*) '.
            'FROM win_ivr '.
            'WHERE vcc_id = :vcc_id AND ivr_id = :ivr_id ',
            array('vcc_id'=>$vid,'ivr_id'=>$ivr_id)
        );

        if (empty($count)) {
            $ret = array(
                'code' => 403,
                'message' => 'IVR流程不存在',
            );
            return new JsonResponse($ret);
        }

        $data = array(
            'ivr_info' => $ivr_info,
            'ivr_content' => $ivr_content,
        );

        $num = $conn->update('win_ivr', $data, array('vcc_id'=>$vid,'ivr_id'=>$ivr_id));

        if ($num > 0) {
//            $win_ip          = $this->container->getParameter('win_ip');
//            $win_web_port    = $this->container->getParameter('win_web_port');
//            $win_system_name = $this->container->getParameter('win_system_name');
//            $exec_result     = file_get_contents("http://$win_ip:$win_web_port/$win_system_name/system.php?act=ivr&vcc_id=$vid");
            //更换成分发
            $result = $this->get("icsoc_core.common.class")->addToChangelogAndSendNoticeToZmqServer($ivr_id, $vid);
            if (!$result) {
                $ret = array(
                    'code' => 404,
                    'message' => '流程配置成功，但未生效',
                    'data'=>$ivr_id,
                );
            } else {
                $ret = array(
                    'code' => 200,
                    'message' => 'ok',
                    'data'=>$ivr_id,
                );
            }
            return new JsonResponse($ret);
        } else {
            $ret = array(
                'code' => 405,
                'message' => '流程配置失败',
            );
            return new JsonResponse($ret);
        }
    }
}
